//
//  CityViewController.m
//  myCar
//
//  Created by 王子洁 on 14/11/4.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "CityViewController.h"
#import "AIMTableViewIndexBar.h"
#import "CityName.h"
#import "NewsViewController.h"
#import "WebColor.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
@interface CityViewController ()<UITableViewDataSource, UITableViewDelegate, AIMTableViewIndexBarDelegate>


@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)AIMTableViewIndexBar *indexBar;

@property (nonatomic, retain)NSMutableArray *cityArr;

@property (nonatomic, retain)NSMutableArray *indexArr;

@property (nonatomic, retain)NSMutableArray *rowNumArr;

@property (nonatomic, retain)NSMutableDictionary *dictionary;

@end

@implementation CityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.cityArr = [NSMutableArray array];
        self.indexArr = [NSMutableArray array];
        self.rowNumArr = [NSMutableArray array];
        self.dictionary = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)dealloc
{
    [_cityArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [WebColor whiteSmoke];
    [self initView];
    [self relodata];
}

- (void)initView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 20, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    self.view.backgroundColor = [WebColor whiteSmoke];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.indexBar = [[AIMTableViewIndexBar alloc] initWithFrame:CGRectMake(300, 20, 20, self.view.frame.size.height - 64 - 80)];
    [self.view addSubview:self.indexBar];
    self.indexBar.delegate = self;
    [_indexBar release];
}

- (void)relodata
{
    MBProgressHUD *hub = [[MBProgressHUD alloc] init];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    NSString *str  = @"http://mrobot.pcauto.com.cn/v2/cms/area_tree";
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [responseObject valueForKey:@"area"];
        for (NSArray *arr1 in arr) {
            CityName *city = [[CityName alloc] init];
            city.pro = [arr1 objectAtIndex:3];
            city.city = [arr1 objectAtIndex:1];
            
            NSMutableString *ms = [[NSMutableString alloc] initWithString:city.city];
            if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
                NSString *mStr = [ms substringToIndex:1];
                if (![self.indexArr containsObject:mStr]) {
                    [self.indexArr addObject:mStr];
                }
                city.index = mStr;
            }
            [self.cityArr addObject:city];
            [city release];
            [ms release];
        }
        for (int i = 0; i < self.indexArr.count; i++) {
            for (int j = 0; j < self.indexArr.count - i - 1; j++) {
                if ([self.indexArr[j] compare:self.indexArr[j + 1]] > 0) {
                    NSString *t = @"0";
                    t = self.indexArr[j + 1];
                    self.indexArr[j + 1] = self.indexArr[j];
                    self.indexArr[j] = t;
                }
            }
        }
        for (int i = 0; i < self.indexArr.count; i++) {
            self.rowNumArr = [NSMutableArray array];
            for (CityName *city in self.cityArr) {
                if ([self.indexArr[i] isEqualToString:city.index]) {
                    [self.rowNumArr addObject:city];
                }
            }
            [self.dictionary setValue:self.rowNumArr forKey:self.indexArr[i]];
        }
        [self.tableView reloadData];
         [hub removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        self.tableView.backgroundView = imageView;
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
        [alertView show];
        [imageView release];
        [alertView release];
    }];
   
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buttonClicked:(UIButton *)button
{
    NSLog(@"点击");
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark tableView 协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    [self.indexBar setIndexes:self.indexArr];
    return self.indexArr.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.indexArr[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = [self.dictionary objectForKey:[self.indexArr objectAtIndex:section]];
    //NSLog(@"========%d", arr.count);
    return arr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse1"];
    if (!cell) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse1"] autorelease];
    }
    
    CityName *city = [[self.dictionary objectForKey:[self.indexArr objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    cell.textLabel.text = city.city;
    return cell;
    
}

- (void)tableViewIndexBar:(AIMTableViewIndexBar *)indexBar didSelectSectionAtIndex:(NSInteger)index{
    if ([self.tableView numberOfSections] > index && index > -1){   // for safety, should always be YES
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]
                              atScrollPosition:UITableViewScrollPositionTop
                                      animated:YES];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CityName *city = [[self.dictionary objectForKey:[self.indexArr objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    [self.delegate passValue:city];
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
